package com.pda.yuanjing.pages.pron.scanf;

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.LoaclBeanIn;
import com.pda.yuanjing.beanout.BaseBeanOut;
import com.pda.yuanjing.beanout.BeanNOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.database.DataBaseControl;
import com.pda.yuanjing.database.InCode;
import com.pda.yuanjing.database.OutCode;
import com.pda.yuanjing.database.RelationCode;
import com.pda.yuanjing.tools.StringUtils;
import com.public_module.basemvp.activity.BaseActivity_noMVP;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.dialogs.ChooseDialog;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ScanfActivity extends BaseActivity_noMVP {
    private String TAG = "ScanfActivity";

    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvbill)
    TextView tvbill;
    @BindView(R.id.tvname)
    TextView tvname;
    @BindView(R.id.tvpname)
    TextView tvpname;
    @BindView(R.id.tvnum)
    TextView tvnum;
    @BindView(R.id.tvcasenum)
    TextView tvcasenum;
    @BindView(R.id.login_id)
    EditText loginId;
    @BindView(R.id.logine)
    Button logine;
    @BindView(R.id.sws)
    Switch sws;
    @BindView(R.id.ivd)
    ImageView ivd;
    @BindView(R.id.tvres)
    TextView tvres;
    @BindView(R.id.tvs)
    TextView tvs;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tvwait)
    TextView tvwait;

    BeanNOut beanNOut = null;
    boolean flag = true;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    String billID = "", billListID = "", productID = "";
    int caseBoxNum = 0, ynum = 0, snum = 0;
    VoiceUtils voiceUtils;
    Gson gson;
    OkHttpClient client;
    ApiYJ apisync;
    int res = -1;
    List<String> codes = new ArrayList<>();
    String dialogTitle = "是否上传数据";
    ChooseDialog chooseDialog1;
    int scanfState = 0;

    protected void initdata() {
        tvTitle.setText("生产关联扫描");
        if (SharedPreferencesManger.getLoacl()) {
            tvRight.setText("导出");
            tvs.setVisibility(View.GONE);
            dialogTitle = "是否导出数据";
        }
        beanNOut = (BeanNOut) getIntent().getSerializableExtra(PDApp.loacl);
        billID = beanNOut.getBillID();
        productID = beanNOut.getProductID();
        billListID = beanNOut.getBillListID();
        ynum = beanNOut.getYnum();
        snum = beanNOut.getSnum();
        caseBoxNum = beanNOut.getCaseBoxNum();
        tvbill.setText( billID);
        tvname.setText(beanNOut.getDesStoreName());
        tvpname.setText( beanNOut.getProductName());
        tvnum.setText(snum + "/" + ynum);
        tvcasenum.setText(codes.size() + "/" + caseBoxNum);
        tvwait.setText(DataBaseControl.getRelationCode(billID,false).size()+"");
        chooseDialog1 = new ChooseDialog(this, "是否开启删除条码", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                chooseDialog1.dismiss();
                flag = false;
                ivd.setImageResource(R.mipmap.icon_check);
            }
        });

        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                        tvs.setText(dataa.getStr());
                        scanfState = dataa.getType();
                        if (scanfState == -1) {
                            tvs.setBackgroundResource(R.color.smalltext);
                        } else {
                            tvs.setBackgroundResource(R.color.green);
                        }
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        if (flag) {
                            if (codes.size() < caseBoxNum ) {
                                if(!StringUtils.checkBoxCode(string)){
                                    voiceUtils.voiceWarn();
                                    tvres.setText("盒码长度不符");
                                    return;
                                }
                                if (snum >= ynum) {
                                    voiceUtils.voiceWarn();
                                    tvres.setText("实扫数已达到应扫数");
                                    return;
                                }
                                for (int i = 0; i < codes.size(); i++) {
                                    if (codes.get(i).equals(string)) {
                                        voiceUtils.voiceWarn();
                                        tvres.setText("盒码重复");
                                        return;
                                    }
                                }
                                if (DataBaseControl.uniqueeBoxCode(billID, string) == 0) {
                                    codes.add(string);
                                    tvcasenum.setText(codes.size() + "/" + caseBoxNum);
                                } else {
                                    voiceUtils.voiceWarn();
                                    tvres.setText("盒码重复");
                                    return;
                                }
                            }
                            if (codes.size() == caseBoxNum) {
                                if(!StringUtils.checkCaseCode(string)){
                                    voiceUtils.voiceWarn();
                                    tvres.setText("箱码长度不符");
                                    return;
                                }
                                if (snum + caseBoxNum > ynum) {
                                    voiceUtils.voiceWarn();
                                    tvres.setText("实扫数已达到应扫数");
                                    return;
                                }
                                if (DataBaseControl.uniqueeCaseCode(billID, string) == 0) {
                                    for (int i = 0; i < codes.size(); i++) {
                                        RelationCode relationCode = new RelationCode();
                                        relationCode.setBillID(billID);
                                        relationCode.setProductID(productID);
                                        relationCode.setCaseCode(string);
                                        relationCode.setBoxCode(codes.get(i));
                                        DataBaseControl.addRelationCode(relationCode);
                                    }
                                    snum = snum + caseBoxNum;
                                    DataBaseControl.updateRelationBill(billID, productID, snum);
                                    codes.clear();
                                    tvnum.setText(snum + "/" + ynum);
                                    tvcasenum.setText(codes.size() + "/" + caseBoxNum);
                                    tvwait.setText(DataBaseControl.getRelationCode(billID,false).size()+"");
                                    return;
                                } else {
                                    voiceUtils.voiceWarn();
                                    tvres.setText("箱码重复");
                                    return;
                                }
                            }
                        } else {
                            if (StringUtils.checkCaseCode(string)) {
                                if (snum < caseBoxNum) {
                                    voiceUtils.voiceWarn();
                                    tvres.setText("实扫数不满足删除条件");
                                    return;
                                }
                                if (DataBaseControl.uniqueeCaseCode(billID, string) == -1) {
                                    DataBaseControl.deleteCaseCode(billID, string);
                                    snum = snum - caseBoxNum;
                                    DataBaseControl.updateRelationBill(billID, productID, snum);
                                    tvnum.setText(snum + "/" + ynum);
                                    tvwait.setText(DataBaseControl.getRelationCode(billID,false).size()+"");
                                    return;
                                } else {
                                    voiceUtils.voiceWarn();
                                    tvres.setText("箱码不存在");
                                    return;
                                }
                            } else if (StringUtils.checkBoxCode(string)) {
                                if (codes.contains(string)) {
                                    codes.remove(string);
                                    tvcasenum.setText(codes.size() + "/" + caseBoxNum);
                                    return;
                                } else {
                                    voiceUtils.voiceWarn();
                                    tvres.setText("当前扫描产品规格中不含此盒码");
                                    return;
                                }
                            } else {
                                voiceUtils.voiceWarn();
                                tvres.setText("数码长度不符");
                                return;
                            }
                        }
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        gson = new Gson();
        client = new OkHttpClient.Builder()
                .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                .followRedirects(false)
                .build();
        apisync = new Retrofit.Builder()
                .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                .client(client)
                .build().create(ApiYJ.class);
        chooseDialog = new ChooseDialog(ScanfActivity.this, dialogTitle, R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                chooseDialog.dismiss();
                showProgress();
                if (SharedPreferencesManger.getLoacl()) {
                    if (download(formatList()) != true) {
                        hideProgress();
                        showMsg("导出失败");
                        return;
                    }
                    DataBaseControl.updateRelationCode(billID,true);
                    hideProgress();
                    showMsg("同步订单成功");
                } else {
                    if(scanfState == -1){
                        hideProgress();
                        showMsg("网络连接异常");
                        return;
                    }
                    if (upload(formatList()) != 0) {
                        hideProgress();
                        showMsg("网络连接异常,上传失败");
                        return;
                    }
                    DataBaseControl.updateRelationCode(billID,true);
                    hideProgress();
                    showMsg("上传订单成功");
                }
                finish();
            }
        });
        WindowManager.LayoutParams lp = chooseDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pron_scanf);
        ButterKnife.bind(this);
        initdata();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
    }

    @OnClick({R.id.iv_title_left, R.id.logine, R.id.tv_right,R.id.ivd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.ivd:
                if (flag) {
                    chooseDialog1.show();
                } else {
                    flag = true;
                    ivd.setImageResource(R.mipmap.icon_nocheck);
                }
                break;
            case R.id.logine:
                String string = loginId.getText().toString();
                if (flag) {
                    if (codes.size() < caseBoxNum) {
                        if(!StringUtils.checkBoxCode(string)){
                            voiceUtils.voiceWarn();
                            tvres.setText("盒码长度不符");
                            return;
                        }
                        if (snum >= ynum) {
                            voiceUtils.voiceWarn();
                            tvres.setText("实扫数已达到应扫数");
                            return;
                        }
                        for (int i = 0; i < codes.size(); i++) {
                            if (codes.get(i).equals(string)) {
                                voiceUtils.voiceWarn();
                                tvres.setText("盒码重复");
                                return;
                            }
                        }
                        if (DataBaseControl.uniqueeBoxCode(billID, string) == 0) {
                            codes.add(string);
                            tvcasenum.setText(codes.size() + "/" + caseBoxNum);
                        } else {
                            voiceUtils.voiceWarn();
                            tvres.setText("盒码重复");
                            return;
                        }
                    }
                    if (codes.size() == caseBoxNum ) {
                        if(!StringUtils.checkCaseCode(string)){
                            voiceUtils.voiceWarn();
                            tvres.setText("盒码长度不符");
                            return;
                        }
                        if (snum + caseBoxNum > ynum) {
                            voiceUtils.voiceWarn();
                            tvres.setText("实扫数已达到应扫数");
                            return;
                        }
                        if (DataBaseControl.uniqueeCaseCode(billID, string) == 0) {
                            for (int i = 0; i < codes.size(); i++) {
                                RelationCode relationCode = new RelationCode();
                                relationCode.setBillID(billID);
                                relationCode.setProductID(productID);
                                relationCode.setCaseCode(string);
                                relationCode.setBoxCode(codes.get(i));
                                DataBaseControl.addRelationCode(relationCode);
                            }
                            snum = snum + caseBoxNum;
                            DataBaseControl.updateRelationBill(billID, productID, snum);
                            codes.clear();
                            tvnum.setText(snum + "/" + ynum);
                            tvcasenum.setText(codes.size() + "/" + caseBoxNum);
                            tvwait.setText(DataBaseControl.getRelationCode(billID,false).size()+"");
                            return;
                        } else {
                            voiceUtils.voiceWarn();
                            tvres.setText("箱码重复");
                            return;
                        }
                    }
                } else {
                    if (StringUtils.checkCaseCode(string)) {
                        if (snum < caseBoxNum) {
                            voiceUtils.voiceWarn();
                            tvres.setText("实扫数不满足删除条件");
                            return;
                        }
                        if (DataBaseControl.uniqueeCaseCode(billID, string) == -1) {
                            DataBaseControl.deleteCaseCode(billID, string);
                            snum = snum - caseBoxNum;
                            DataBaseControl.updateRelationBill(billID, productID, snum);
                            tvnum.setText(snum + "/" + ynum);
                            tvwait.setText(DataBaseControl.getRelationCode(billID,false).size()+"");
                            return;
                        } else {
                            voiceUtils.voiceWarn();
                            tvres.setText("箱码不存在");
                            return;
                        }
                    } else if (StringUtils.checkBoxCode(string)) {
                        if (codes.contains(string)) {
                            codes.remove(string);
                            tvcasenum.setText(codes.size() + "/" + caseBoxNum);
                            return;
                        } else {
                            voiceUtils.voiceWarn();
                            tvres.setText("当前扫描产品规格中不含此盒码");
                            return;
                        }
                    } else {
                        voiceUtils.voiceWarn();
                        tvres.setText("数码长度不符");
                    }
                }
                break;
            case R.id.tv_right:
                List<RelationCode> list = DataBaseControl.getRelationCode(billID,false);
                if (list == null || list.size() == 0) {
                    voiceUtils.voiceWarn();
                    tvres.setText("当前订单没有待上传数码");
                    return;
                }
                chooseDialog.show();
                break;
        }
    }

    List<LoaclBeanIn.DataBean> formatList() {
        LoaclBeanIn.DataBean dataBean = null;
        List<LoaclBeanIn.DataBean> listt = new ArrayList<>();
        List<RelationCode> listtemp = DataBaseControl.getRelationCode(billID);
        for (int i = 0; i < listtemp.size(); i++) {
            if (i == 0) {
                dataBean = new LoaclBeanIn.DataBean();
                dataBean.setCasecode(listtemp.get(i).getCaseCode());
                dataBean.setBoxcode(listtemp.get(i).getBoxCode());
                if(!listtemp.get(i).getFlag()){
                    listt.add(dataBean);
                }
            } else {
                if (dataBean.getCasecode().equals(listtemp.get(i).getCaseCode())) {
                    dataBean.setBoxcode(dataBean.getBoxcode() + "," + listtemp.get(i).getBoxCode());
                } else {
                    dataBean = new LoaclBeanIn.DataBean();
                    dataBean.setCasecode(listtemp.get(i).getCaseCode());
                    dataBean.setBoxcode(listtemp.get(i).getBoxCode());
                    if(!listtemp.get(i).getFlag()){
                        listt.add(dataBean);
                    }
                }
            }
        }
        for (int i = 0; i < listt.size(); i++) {
            listt.get(i).setCasecode(listt.get(i).getCasecode() + ";" + listt.get(i).getBoxcode());
        }
        return listt;
    }

    public int upload(List<LoaclBeanIn.DataBean> list) {
        try {
            res = -1;
            LoaclBeanIn loaclBeanIn = new LoaclBeanIn();
            loaclBeanIn.setAction("UpdateCodesBatch");
            loaclBeanIn.setCid(SharedPreferencesManger.getCid());
            loaclBeanIn.setUserID(SharedPreferencesManger.getUid());
            loaclBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            loaclBeanIn.setBillID(billID);
            loaclBeanIn.setBillCode(billID);
            loaclBeanIn.setDesStoreID(SharedPreferencesManger.getStoreID());
            loaclBeanIn.setBillType(11);
            loaclBeanIn.setCreateTime(beanNOut.getCreateTime());
            loaclBeanIn.setBillListID(billListID);
            loaclBeanIn.setProductID(productID);
            loaclBeanIn.setCodeArray(list);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(loaclBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            BaseBeanOut baseBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), BaseBeanOut.class);
                            if (baseBeanOut.getErrcode() == 0) {
                                res = 0;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return res;
        }
    }

    public boolean download(List<LoaclBeanIn.DataBean> list) {
        try {
            LoaclBeanIn loaclBeanIn = new LoaclBeanIn();
            loaclBeanIn.setAction("UpdateCodesBatch");
            loaclBeanIn.setCid(SharedPreferencesManger.getCid());
            loaclBeanIn.setUserID(SharedPreferencesManger.getUid());
            loaclBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            loaclBeanIn.setBillID(billID);
            loaclBeanIn.setBillCode(billID);
            loaclBeanIn.setDesStoreID(SharedPreferencesManger.getStoreID());
            loaclBeanIn.setBillType(11);
            loaclBeanIn.setCreateTime(beanNOut.getCreateTime());
            loaclBeanIn.setBillListID(billListID);
            loaclBeanIn.setProductID(productID);
            loaclBeanIn.setCodeArray(list);
            String str = gson.toJson(loaclBeanIn);
            return StringUtils.writeTxtToFile(this, str, "/PDADataExport/scscan.txt");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
